import { View, Text, Checkbox, CheckboxGroup } from '@tarojs/components'
import Taro, { useLoad,useDidShow } from '@tarojs/taro'
import './index.scss'
import { useState } from 'react'
import { request } from "@/utils/request";
import { AtIcon } from 'taro-ui'
let resCompanyList = [] as any
let path = '/pages/selectMerchant/index/'
let isReadAgreementKey = path + 'isReadAgreement'

export default function SelectMerchant () {
  const [areaId, setAreaId] = useState<any>('')
  const [resCompanyList, setResCompanyList] = useState<any>([])
  const [companyTypeList, setCompanyTypeList] = useState<any>([])
  const [isAgreeAgreement, setIsAgreeAgreement] = useState(false)
  const [selectedCompanyIds, setSelectedCompanyIds] = useState<any>([])
  // 是否阅读过协议
  const [isReadAgreement, setIsReadAgreement] = useState(false)
    function getMerchantList(){
    request({
     url: '/api/points/company/getCompanyList',
     method: 'GET',
     success: (data) => {
       setResCompanyList(data)
       console.log('🚀 ~ getMerchantList ~ data:', data)
      //  按照companyType分类
       let companyTypeMap = {}
       data.forEach((company: any) => {
         if(!companyTypeMap[company.companyType]){
           companyTypeMap[company.companyType] = []
         }
         companyTypeMap[company.companyType].push(company)
       })
      //  console.log('🚀 ~ getMerchantList ~ companyTypeMap:', companyTypeMap)
       let companyTypeList = [] as any
       for(let key in companyTypeMap){
         companyTypeList.push({
           companyType: key,
           companyTypeName: companyTypeName(key),
           companyList: companyTypeMap[key]
         })
       }
       setCompanyTypeList(companyTypeList)
     }
    })
  }
  function companyTypeName(companyType: any){
    switch(companyType){
      case '1':
        return '通信公司'
      case '2':
        return '连锁加油站'
      default:
        return '其他'
    }
  }
 
  function readArticle(){
    Taro.navigateTo({
      url:'/pages/jiFenAgreement/index',
      success:()=>{
        setIsReadAgreement(true)
        Taro.setStorageSync(isReadAgreementKey, true)
      }
    })
  }
  function articleCheckboxChange(event){
    console.log('event.detail.value:',event.detail.value)
    if(!isReadAgreement){
      readArticle()
      return 
    }
    if(event.detail.value.length>0){
      setIsAgreeAgreement(true)
    }else{
      setIsAgreeAgreement(false)
    }
  }
  function pickCompany(company: any){
    if(selectedCompanyIds.includes(company.companyId)){
      setSelectedCompanyIds(selectedCompanyIds.filter(item=>item!==company.companyId))
    }else{
      setSelectedCompanyIds([...selectedCompanyIds, company.companyId])
    }
  }
  function submitDataToServer(){
    let submitData = selectedCompanyIds.map(companyId=>{
      let companyData = resCompanyList.find(item=>{
        return item.companyId == companyId
      })
      // console.log('🚀 ~ submitData ~ resCompanyList:', resCompanyList)
      // console.log('🚀 ~ submitData ~ companyData:', companyData)
      if(companyData){
        return {
          companyId:companyId,
          points:companyData.points,
          pointsCompanyAreaId:areaId,
          price:companyData.price,
          status:companyData.status
        }
      }
      
    })
    request({
      url: '/api/points/company/submit',
      method: 'POST',
      data: submitData,
      success: (data) => {
        Taro.showModal({
          title: '提示',
          content: '提交成功',
          showCancel: false,
          confirmText: '我知道了',
          success: (res) => {
            if (res.confirm){
              Taro.reLaunch({
                url: '/pages/index/index'
              })
            }
          }
        })
      }
    })

  }
  function submitData(){
    if(!isAgreeAgreement){
      Taro.showToast({
        title: '请先阅读并同意协议',
        icon: 'none'
      })
      return
    }
    if(selectedCompanyIds.length==0){
      Taro.showToast({
        title: '请选择要兑换积分的企业',
        icon: 'none'
      })
      return
    }
    Taro.showModal({
      title: '提示',
      content: '提交后不可修改或再次报名',
      success: (res) => {
        if (res.confirm) {
          submitDataToServer()
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
    
  }
  useLoad((options) => {
    console.log('Page loaded.')
    setAreaId(options.areaId)
    getMerchantList()
    
    
  })
  useDidShow(()=>{
    let storageAgree = Taro.getStorageSync('pages/jiFenAgreement/index/agreeInsuranceAgreement')
    if(storageAgree){
      setIsAgreeAgreement(true)
    }
    let storageIsReadAgreement = Taro.getStorageSync(isReadAgreementKey)
    if(storageIsReadAgreement){
      setIsReadAgreement(true)
    }
  })

  return (
    <View className='selectMerchant'>
      <View className='tip'>请选择您要兑换积分的企业</View>
      <View className='category-list mt32'>
        {
          companyTypeList && companyTypeList.map((companyTypeItem: any) =>{
            return <View className='category-item'>
              <View className='category-name'>{companyTypeItem.companyTypeName+(companyTypeItem.companyTypeName==='通信公司' ? '（仅限本账号手机号）':'')}</View>
              <View className='merchant-list'>
                {
                  companyTypeItem.companyList && companyTypeItem.companyList.map(companyItem=>{
                    return <View className={['merchant-item', selectedCompanyIds.includes(companyItem.companyId) ? 'selected' : ''].join(' ')} onClick={()=>{pickCompany(companyItem)}}>
                      {selectedCompanyIds.includes(companyItem.companyId) && <AtIcon className='check-icon' value='check' size='12' color='#67C23A'></AtIcon>}
                      <View className='merchant-name'>{companyItem.companyName}</View>
                      <View className='points'>可转:{companyItem.points}分</View>
                      <View className='money'>价值:{companyItem.price / 100 }元</View>
                    </View>
                  })
                }
              </View>
            </View>
          })
        }
      </View>
      <View className='rule-wrap'>
        <View className='title'>公益服务费提醒</View>
        <View className='des'>为保障项目可持续运营、覆盖技术研发、平台维护、客户服务及 AI 健康管理等增值服务成本，将向用户收取一定比例服务费，标准如下:</View>
        <View className='des'>
          <Text className='bold'>1、平台运营服务费：</Text>由万户良方收取，按本次兑换积分对应资金价值的8% 收取，用于技术服务、平台运营及 AI健康管理等增值服务;
        </View>
        <View className='des'>
          <Text className='bold'>2、公益管理费：</Text>由爱尔公益基金会收取，为兑换积分对应资金价值的6.44%(即扣除 8% 平台运营服务费后剩余部分的 7%)，用于专项基金管理及公益项目统筹。
        </View>
        <View className='des'>
          <Text className='bold'>费用示例</Text>
        </View>
        <View className='des'>
          兑换积分价值 100 元
        </View>
        <View className='des'>
          平台运营服务费:100元x8%=8元
        </View>
        <View className='des'>
          公益管理费:100元x6.44%=6.44元
        </View>
        <View className='des'>
          您最终可用于缴纳医保的金额:100元-8元-6.44元=85.56元
        </View>
      </View>
      <View className='fixed-bottom'>
        <View className='inner'>
          <View className='article'>
            <CheckboxGroup onChange={ articleCheckboxChange}>
              <Checkbox className='form-checkbox' value="0" checked= {isAgreeAgreement}></Checkbox>
              <Text className="form-tip-text" onClick={ readArticle }>
                阅读并同意《积分宝积分兑换服务协议》
              </Text>
            </CheckboxGroup>
            
          </View>
          <View className='btn' onClick={submitData}>同意协议并提交</View>
        </View>
        
      </View>
    </View>
  )
}
